package com.myccb.app.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.myccb.app.R;
import com.myccb.app.base.RequestManager;
import com.myccb.app.base.BaseActivity;
import com.myccb.app.base.BasePagerAdapter;
import com.myccb.app.widget.CommonDialog;
import com.myccb.app.widget.CommonToolBar;
import com.myccb.app.widget.EditTextClearable;
import com.myccb.app.widget.LoadingCountdownDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class RegisterActivity extends BaseActivity {

    private ViewPager stepsContainer;
    private View registerStep1Layout;
    private View registerStep2Layout;
    private View registerStep3Layout;

    private Toolbar toolbar;
    private CommonToolBar commonToolBar;

    private Bitmap vcodeImg;

    private ImageView vcodeView;

    private TextView nextStepBtn;

    private int currentStep;


    private EditTextClearable etc_userName;
    private EditTextClearable etc_BCNum;
    private EditTextClearable etc_last4ofPhoneNum;
    private EditTextClearable etc_vcode;

    private EditTextClearable etc_BCPassword;
    private EditTextClearable etc_phoneVcode;

    private EditTextClearable etc_settingPassword;
    private EditTextClearable etc_checkPassword;


    private String userName;
    private String BCNum;
    private String last4ofPhoneNum;
    private String vcode;


    private String BCPassword;
    private String phoneVcode;


    private String settingPassword;
    private String checkPassword;


    private String phoneNum;


    private TextView sendPhoneVcodeMsg;


    private TextView resetPhoneVcodeBtn;


    private TextView step3ErrorMsg;

    private CommonDialog errorMsgDialog;

    //private int action;

    private LoadingCountdownDialog loadingCountdownDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        currentStep=0;
    }
    private void initView(){
        commonToolBar=findViewById(R.id.common_toolbar);
        toolbar=commonToolBar.getToolbar();
        setSupportActionBar(toolbar);
        commonToolBar.setOnLeftButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.slide_out_right);
            }
        });

        stepsContainer=findViewById(R.id.register_steps_container);
        nextStepBtn=findViewById(R.id.btn_next_step);

        nextStepBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (currentStep){
                    case 1:
                        userName=etc_userName.getText().toString();
                        BCNum=etc_BCNum.getText().toString();
                        last4ofPhoneNum=etc_last4ofPhoneNum.getText().toString();
                        vcode=etc_vcode.getText().toString();
                        new RegisterTask().execute(1);
                        break;
                    case 2:
                        BCPassword=etc_BCPassword.getText().toString();
                        phoneVcode=etc_phoneVcode.getText().toString();
                        new RegisterTask().execute(2);
                        break;
                    case 3:
                        settingPassword=etc_settingPassword.getText().toString();
                        checkPassword=etc_checkPassword.getText().toString();
                        new RegisterTask().execute(3);
                        break;
                }
            }
        });

        LayoutInflater inflater=getLayoutInflater();

        registerStep1Layout=inflater.inflate(R.layout.register_step1_layout,null);
        registerStep2Layout=inflater.inflate(R.layout.register_step2_layout,null);
        registerStep3Layout=inflater.inflate(R.layout.register_step3_layout,null);

        vcodeView=registerStep1Layout.findViewById(R.id.imageview_vcode);

        etc_userName=registerStep1Layout.findViewById(R.id.edittext_name);
        etc_BCNum=registerStep1Layout.findViewById(R.id.edittext_cardnum);
        etc_last4ofPhoneNum=registerStep1Layout.findViewById(R.id.edittext_end4_of_phone);
        etc_vcode=registerStep1Layout.findViewById(R.id.edittext_vcode);

        etc_userName.addOnTextChangeListener(new RegisterTextWatcher());
        etc_BCNum.addOnTextChangeListener(new RegisterTextWatcher());
        etc_last4ofPhoneNum.addOnTextChangeListener(new RegisterTextWatcher());
        etc_vcode.addOnTextChangeListener(new RegisterTextWatcher());

        etc_BCPassword=registerStep2Layout.findViewById(R.id.bc_password);
        etc_phoneVcode=registerStep2Layout.findViewById(R.id.phone_vcode);
        sendPhoneVcodeMsg=registerStep2Layout.findViewById(R.id.send_phone_vcode_msg);
        resetPhoneVcodeBtn=registerStep2Layout.findViewById(R.id.reset_phone_vcode);

        etc_BCPassword.addOnTextChangeListener(new RegisterTextWatcher());
        etc_phoneVcode.addOnTextChangeListener(new RegisterTextWatcher());

        etc_phoneVcode.setEnabled(false);
        resetPhoneVcodeBtn.setEnabled(false);

        etc_settingPassword=registerStep3Layout.findViewById(R.id.edittext_password);
        etc_checkPassword=registerStep3Layout.findViewById(R.id.edittext_password2);
        step3ErrorMsg=registerStep3Layout.findViewById(R.id.error_msg);
        step3ErrorMsg.setText("");
        etc_settingPassword.addOnTextChangeListener(new RegisterTextWatcher());
        etc_checkPassword.addOnTextChangeListener(new RegisterTextWatcher());

        stepsContainer.setAdapter(new BasePagerAdapter() {
            private View[] stepPages={
                    registerStep1Layout,registerStep2Layout,registerStep3Layout
            };
            @Override
            public View getView(ViewGroup container, int position) {
                return stepPages[position];
            }
            @Override
            public int getCount() {
                return stepPages.length;
            }
        });

        stepsContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        stepsContainer.setCurrentItem(0);


        loadingCountdownDialog=new LoadingCountdownDialog(this);
        errorMsgDialog=new CommonDialog(this);

        vcodeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new RegisterTask().execute(0);
            }
        });

        new RegisterTask().execute(0);
    }

    private class RegisterTask extends AsyncTask<Integer, Void, Integer> {


        @Override
        protected void onPreExecute() {
            loadingCountdownDialog.show(30);
        }

        @Override
        protected Integer doInBackground(Integer... action) {

            switch (action[0]){
                case 0:
                    vcodeImg=getVcode();
                    return 0;
                case 1:
                    String result=registerStep1();
                    if (result.length()<=2){
                        if (Integer.parseInt(result)<0)
                            return Integer.parseInt(result);
                        return Integer.parseInt(result)*10+1;
                    }
                    else{

                        phoneNum=result;
                        return 1;
                    }
                case 2:
                    result=registerStep2();
                    if (result.length()<=2){
                        if (Integer.parseInt(result)<0)
                            return Integer.parseInt(result);
                        else
                            return Integer.parseInt(result)*10+2;
                    }
                    else
                        return 2;
                case 3:
                    result=registerStep3();
                    if (result.length()<=2){
                        if (Integer.parseInt(result)<0)
                            return Integer.parseInt(result);
                        else
                            return Integer.parseInt(result)*10+3;
                    }
                    else
                        return 3;
            }
            return 0;
        }
        @Override
        protected void onPostExecute(Integer action) {
            loadingCountdownDialog.dismiss();
            if (action<0){
                showErrorMsg("提交参数错误！请检查网络连接是否正常",action);
                return;
            }
            switch (action%10){
                case 0:
                    vcodeView.setImageBitmap(vcodeImg);
                    etc_vcode.setText("");
                    currentStep=1;
                    break;
                case 1:
                    int code=action/10;
                    if (code==0){
                        currentStep=2;
                        sendPhoneVcodeMsg.setText("已向您"+phoneNum.substring(0,4)+"***"+phoneNum.substring(7,11)+"的手机号发送验证码");
                        nextStepBtn.setEnabled(false);
                        commonToolBar.setTitle("验证银行卡密码");
                        stepsContainer.setCurrentItem(1);
                    }
                    else{
                        showStep1Error(code);
                        new RegisterTask().execute(0);
                    }
                    break;
                case 2:
                    code=action/10;
                    if (code==0){
                        currentStep=3;
                        stepsContainer.setCurrentItem(2);
                        commonToolBar.setTitle("设置手机银行密码");
                        nextStepBtn.setEnabled(false);
                        nextStepBtn.setText("完成");
                    }
                    else{
                        showStep2Error(code);
                        //new RegisterTask().execute(0);
                    }
                    break;
                case 3:
                    code=action/10;
                    if (code==0){
                        Toast.makeText(getApplicationContext(),"成功开通手机银行",Toast.LENGTH_LONG).show();
                        Intent intent=new Intent(RegisterActivity.this,FirstLoginActivity.class);
                        startActivity(intent);
                        finish();
//                        currentStep=3;
//                        stepsContainer.setCurrentItem(2);
//                        getSupportActionBar().setTitle("设置手机银行密码");
//                        nextStepBtn.setEnabled(false);
//                        nextStepBtn.setText("完成");
                    }
                    else{
                        showStep1Error(code);
                        //new RegisterTask().execute(0);
                    }
            }
        }
    }

    private Bitmap getVcode(){
        HashMap<String,String> postParams=new HashMap<>();
        postParams.put("action","getVcode");
        byte[] bytes= RequestManager.getInstance(getApplicationContext()).postBySynWithForm("register.php",postParams);
        Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
        return bitmap;
    }

    private String registerStep1(){
        HashMap<String,String> postParams=new HashMap<>();
        postParams.put("action","step1");
        postParams.put("vcode",vcode);
        postParams.put("bcNum",BCNum);
        postParams.put("last4ofPhoneNum",last4ofPhoneNum);
        postParams.put("userName",userName);
        String result=RequestManager.getInstance(getApplicationContext()).requestSyn("register.php",RequestManager.TYPE_POST_FORM,postParams);
        Log.d("register",result);
        JSONObject jb = null;
        try {
            jb = new JSONObject(result);
            int status=jb.getInt("status");
            if(status==0){
                int code=jb.getInt("code");

                result=""+code;
            }
            else if (status==1){
                jb=jb.getJSONObject("result");
                result=jb.getString("phoneNum");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return result;
    }

    private String registerStep2(){
        HashMap<String,String> postParams=new HashMap<>();
        postParams.put("action","step2");
        postParams.put("bcPassword",BCPassword);
        String result=RequestManager.getInstance(getApplicationContext()).requestSyn("register.php",RequestManager.TYPE_POST_FORM,postParams);
        Log.d("register",result);
        JSONObject jb = null;
        try {
            jb = new JSONObject(result);
            int status=jb.getInt("status");
            if(status==0){
                int code=jb.getInt("code");
                result=""+code;
            }
            else if (status==1){
                jb=jb.getJSONObject("result");
                result=jb.getString("phoneNum");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

    private String registerStep3() {
        HashMap<String, String> postParams = new HashMap<>();
        postParams.put("action", "endStep");
        postParams.put("password",settingPassword);
        postParams.put("password2",checkPassword);
        postParams.put("phoneNum",phoneNum);
        String result=RequestManager.getInstance(getApplicationContext()).requestSyn("register.php",RequestManager.TYPE_POST_FORM,postParams);
        Log.d("register",result);
        JSONObject jb = null;
        try {
            jb = new JSONObject(result);
            int status=jb.getInt("status");
            if(status==0){
                int code=jb.getInt("code");
                result=""+code;
            }
            else if (status==1){
                jb=jb.getJSONObject("result");
                result=jb.getString("phoneNum");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void showStep1Error(int code){
        switch (code){
            case 2:
                showErrorMsg("验证码错误！请重新输入",100+code);
                break;
            case 3:
                showErrorMsg("银行账户不存在！请核实后重试",100+code);
                break;
            case 4:
                showErrorMsg("个人信息不正确！请核实后重试",100+code);
                break;

        }
    }
    private int errorPassCount=0;
    private void showStep2Error(int code){
        switch (code){
            case 2:
                errorPassCount++;
                showErrorMsg("银行卡密码错误"+errorPassCount+"次！今日输入错误三次您的银行卡将被锁定，请认真核实后重试",200+code);
                break;
            case 7:
                showErrorMsg("由于您今日密码输入错误达到3次，你的银行卡已被锁定，请等待24小时后重试或到当地柜台咨询详细信息",200+code);
                errorMsgDialog.setOnOkBtnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        errorMsgDialog.dismiss();
                        finish();
                    }
                });
                break;
        }
    }


    private void showErrorMsg(String msg,int code){
        errorMsgDialog.showMessage(msg,"错误代码:"+code);
    }


    class RegisterTextWatcher implements EditTextClearable.OnTextChangeListener{
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            switch (currentStep){
                case 1:
                    if (etc_userName.getText().toString().equals("")){
                        nextStepBtn.setEnabled(false);
                        return;
                    }
                    if (etc_BCNum.getText().toString().length()<19){
                        nextStepBtn.setEnabled(false);
                        return;
                    }
                    if (etc_last4ofPhoneNum.getText().toString().length()!=4){
                        nextStepBtn.setEnabled(false);
                        return;
                    }
                    if (etc_vcode.getText().toString().length()!=5){
                        nextStepBtn.setEnabled(false);
                        return;
                    }
                    nextStepBtn.setEnabled(true);
                    break;
                case 2:
                    if (etc_BCPassword.getText().toString().length()!=6){
                        nextStepBtn.setEnabled(false);
                        return;
                    }
                    if (etc_phoneVcode.getText().toString().length()!=6){
                        nextStepBtn.setEnabled(false);
                        return;
                    }
                    nextStepBtn.setEnabled(true);
                    break;
                case 3:
                    if (etc_settingPassword.getText().toString().length()<6){
                        nextStepBtn.setEnabled(false);
                        step3ErrorMsg.setText("密码长度不能小于6位");
                        return;
                    }
                    if (etc_checkPassword.getText().toString().length()==0){

                        nextStepBtn.setEnabled(false);
                        step3ErrorMsg.setText("请再次输入密码以确认无误");
                        return;

                    }
                    if (!etc_settingPassword.getText().toString().equals(etc_checkPassword.getText().toString())){
                        nextStepBtn.setEnabled(false);
                        step3ErrorMsg.setText("两次密码输入不一致");
                        return;
                    }

                    nextStepBtn.setEnabled(true);
                    step3ErrorMsg.setText("");
                    break;
            }
            /*if (et_password.getText()==null||et_vcode.getText()==null||et_phone.getText()==null){
                loginBtn.setEnabled(false);
                return;
            }
            if (!et_phone.getText().toString().matches(phoneNumPattern)){
                loginBtn.setEnabled(false);
                return;
            }
            if (et_vcode.getText().toString().length()<4){
                loginBtn.setEnabled(false);
                return;
            }
            if (et_password.getText().toString().length()<6){
                loginBtn.setEnabled(false);
                return;
            }
            loginBtn.setEnabled(true);*/
        }
    }
}